﻿using System;
using System.Collections.Generic;

namespace SharpDepend.Classes.Threading
{
    /// <summary>
    /// Share a list for reading to several threads.
    /// This do not use lock mechanism but will not be accurate. There will be situation when any thread will read a dead/unupdated object.
    /// </summary>
    public class ListSharer<T>
    {
        private IList<T> mList;
        private T[] mListForReading;
        private int mLength;

        public ListSharer(IList<T> list)
        {
            mList = list;

            mListForReading = new T[mList.Count];
        }

        /// <summary>
        /// This will copy source list to a secondary list, that can be readed at anytime.
        /// </summary>
        public void ListHasUpdated()
        {
            T[] tmp = mListForReading;

            if (mList.Count > mListForReading.Length)
            {
                mListForReading = new T[mList.Count * 2];
            }

            Array.Copy(tmp, mListForReading, mList.Count);
            Array.Clear(mListForReading, mList.Count, mListForReading.Length - mLength);

            mLength = mList.Count;
        }

        public int Count
        {
            get
            {
                return mLength;
            }
        }
        
        public T this[int index]
        {
            get
            {
                return mListForReading[index];
            }
        }
    }
}
